package com.cssy.xxkj.logic.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONArray;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.xxkj.basic.constants.Constants;
import com.cssy.xxkj.basic.entity.BasicCompanyTestDO;
import com.cssy.xxkj.basic.entity.BasicCurrencyTestDO;
import com.cssy.xxkj.basic.service.IBasicCompanyTestService;
import com.cssy.xxkj.basic.service.IBasicCurrencyTestService;
import com.cssy.xxkj.basic.service.IBasicUtilService;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.entity.LogicPurchaseDO;
import com.cssy.xxkj.logic.entity.LogicPurchaseItemDO;
import com.cssy.xxkj.logic.entity.LogicPurchaseWareDO;
import com.cssy.xxkj.logic.entity.vo.LogicPurchaseItemVo;
import com.cssy.xxkj.logic.service.ILogicPurchaseItemService;
import com.cssy.xxkj.logic.service.ILogicPurchaseService;
import com.cssy.xxkj.logic.service.ILogicPurchaseWareItemService;
import com.cssy.xxkj.logic.service.ILogicPurchaseWareService;
import com.cssy.xxkj.logic.util.OftenMothedUtil;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.ExcelUtil;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.SessionUtil;
import com.plat.util.json.AjaxUtil;
import com.plat.util.json.OutJsonGrid;

/**
 * 采购订单controller
 * @author zeyong.gui
 *
 */
@Controller
@RequestMapping("/logic/purchase")
public class PurchaseController extends BaseController<LogicPurchaseDO> { 
	
	private static final String MANGER = "/xxkj/logic/purchase/PurchaseManager";
	private static final String EIDT = "/xxkj/logic/purchase/PurchaseOperation";
	
	@Resource(name = "logicPurchaseWareService")
	ILogicPurchaseWareService logicPurchaseWareService;
	
	@Resource(name = "logicPurchaseWareItemService")
	ILogicPurchaseWareItemService logicPurchaseWareItemService;
	
	@Resource(name = "logicPurchaseService")
	ILogicPurchaseService logicPurchaseService;
	
	@Resource(name = "logicPurchaseItemService")
	ILogicPurchaseItemService logicPurchaseItemService;
	
	@Resource(name = "basicUtilService")
	IBasicUtilService basicUtilService;
	
	@Resource(name = "basicCompanyTestService")
	IBasicCompanyTestService basicCompanyTestService;
	

	@Resource(name = "basicCurrencyTestService")
	private IBasicCurrencyTestService basicCurrencyTestService;

	@Resource(name = "oftenMothedUtil")
	private OftenMothedUtil oftenMothedUtil;
	
	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANGER;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander = new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		hander.getWheres(scs);
		scs=this.oftenMothedUtil.getNoFinishConditions(scs, "zd011WhStatus", BillStatusUtil.PCSWH_BILL_STATUS_TWO);
		if(StringUtils.isBlank(scs.getOrderBy())){
			scs.setOrderBy(" bizCreatorDate desc ");
		}
		SearchResult result = logicPurchaseService.findListByExample(scs);
		OutJsonGrid out = new OutJsonGrid(result);
		out.printJSon(response);
	}

	@Override
	public String operationForm(HttpServletRequest request, @PathVariable String id,
			@PathVariable String flag, Model model) throws Exception {
		if (OperationFlag.ADD.equals(flag)) {
			model.addAttribute("flag", "ADD");
		} else {
			LogicPurchaseDO purchase = logicPurchaseService.findListById(id);
			if(purchase!=null){
				BasicCompanyTestDO comp =  basicCompanyTestService.findListById(purchase.getZd002SupeId());
				BasicCurrencyTestDO curr=  basicCurrencyTestService.findListById(purchase.getZd003CurrencyId());
				model.addAttribute("comp", comp);
				model.addAttribute("curr",curr);
			}
			model.addAttribute("purchase", purchase);
		}
		
		//所有供应商
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty(null);
		scs.addCondition("zd032Type", Constants.COMPANY_TYPE_COMP);
		List<BasicCompanyTestDO> compList = basicUtilService.resultCompany(scs);
		model.addAttribute("compList", compList);
		//所有币种
//		SearchConditions cscs = new SearchConditions();
//		cscs.setRemovedProperty(null);
//		List<BasicCurrencyTestDO> cucyList = basicUtilService.resultCurrency(cscs);
//		model.addAttribute("cucyList", cucyList);
		return EIDT;
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicPurchaseDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try{
			String itemdata = request.getParameter("itemdata");
			if(StringUtils.isBlank(itemdata)){
				bodyMap.isFail();
				bodyMap.configWebInfor("产品列表不能为空！");
				return bodyMap.modelMap;
			}
			logicPurchaseService.purchaseSave(request, curAP);
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
		}catch(Exception e){
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()+ e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
			String ids = request.getParameter("ids");
			String[] fields=ids.split(",");
			for(String field : fields){
				if(StringUtils.isBlank(field)){
					continue;
				}else{
					logicPurchaseService.deleteBizRemoved(field);
				}
			}
			bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
		}
		return bodyMap.modelMap;
	}
	
	/**
	 * 根据供应商ID取得供应商
	 * @param response
	 * @param gysCode
	 */
	@RequestMapping("/getGysInfo")
	public void getGysInfo(HttpServletResponse response,@RequestParam("gysId") String gysId){
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty(null);
		
		scs.addCondition("id",gysId,SearchCondition.OP_EQUAL);
		List<BasicCompanyTestDO> bc = basicUtilService.resultCompany(scs);
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("gys", bc.get(0));
		AjaxUtil.printJSonArr(response, JSONArray.toJSONString(map));
	}
	
	/**
	 * 根据供应商ID取得供应商
	 * @param response
	 * @param gysCode
	 */
	@RequestMapping("/getCurrencyInfo")
	public void getCurrencyInfo(HttpServletResponse response,@RequestParam("currencyId") String currencyId){
		SearchConditions scs = new SearchConditions();
		scs.setRemovedProperty(null);
		scs.addCondition("id",currencyId,SearchCondition.OP_EQUAL);
		List<BasicCurrencyTestDO> bc = basicUtilService.resultCurrency(scs);
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("currency", bc.get(0));
		AjaxUtil.printJSonArr(response, JSONArray.toJSONString(map));
	}

	/**
	 * 查询采购订单的行记录
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/gridItems")
	public void gridItems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String id = request.getParameter("id");
		if(StringUtils.isNotBlank(id)){
			LogicPurchaseDO purchase = logicPurchaseService.findListById(id);
			SearchConditions scs = new SearchConditions();
			scs.setRemovedProperty(null);//判断是否有删除标识
			if(purchase!=null && StringUtils.isNotBlank(purchase.getId())){
				scs.addCondition("zd001PurchaseId", purchase.getId(), SearchCondition.OP_EQUAL);
			}
			List<LogicPurchaseItemDO> pusItemList = logicPurchaseItemService.findListByExample(scs).getResults();
			OutJsonGrid out = new OutJsonGrid(pusItemList);
			out.printJSon(response);
		}
	}
	/**
	 * 采购订单导出功能
	 */
	@RequestMapping("/exportExcel")
	public void exportExcel(HttpServletRequest request,HttpServletResponse response){
		String id= request.getParameter("id");
		
		List<LogicPurchaseItemVo> vo= logicPurchaseItemService.exportExcel(id);
		BasicCompanyTestDO comp =  basicCompanyTestService.findListById(
				logicPurchaseService.findListById(id).getZd002SupeId());
		for(LogicPurchaseItemVo v:vo){
			v.setZd003ZhName(comp.getZd003ZhName());
		}
		ExcelUtil.toExcel(vo, "采购订单编号:zd020Code┋PI号:zd012PiCode"
				+ "┋客户名称:zd022AccountName┋供应商名称:zd003ZhName┋物料编号:zd003Code┋"
				+ "物料名称:zd004Name┋物料型号:zd006Model┋物料尺寸:zd023Size"
				+ "┋物料颜色:zd021Color┋物料材质:zd022Quality┋物料单位:zd009Unit"
				+ "┋物料数量:zd011Quatity┋物料单价:zd012Price┋物料描述:zd025Descript"
				+ "┋采购日期:zd019OrderDate┋收货日期:zd021AcceptDate","采购订单",response);
	}
	/**
	 * 驳回未入库的采购订单
	 */
	@RequestMapping("/deleteBack")
	public void deleteBack(HttpServletRequest request,HttpServletResponse response){
		String id= request.getParameter("id");
		Map<String, Object> msg= new HashMap<String, Object>();
		//获得采购订单的状态
		try {
			LogicPurchaseDO ld=logicPurchaseService.findListById(id);
			if(ld.getZd011WhStatus().equals(BillStatusUtil.PCSWH_BILL_STATUS_ZERO)){
				SearchConditions scs= new SearchConditions();
				scs.addCondition("zd001PcsId", id);
				//找到所有的采购入库单
				List<LogicPurchaseWareDO> lwd=logicPurchaseWareService.findListByExample(scs).getResults();
				for(LogicPurchaseWareDO lpd:lwd){
					//删除主表记录
					lpd.setRemoved(1l);
					logicPurchaseWareService.update(lpd, SessionUtil.getUser(request));
				}
				//更改销售订单状态
				ld.setZd011Status(BillStatusUtil.PHS_BILL_STATUS_FOUR);//驳回
				logicPurchaseService.update(ld, SessionUtil.getUser(request));
				msg.put("msg", "yes");
			}else{
				msg.put("msg", "no");
			}
		} catch (Exception e) {
			msg.put("msg", "no");
		}		
		OutJsonGrid out= new OutJsonGrid(msg);
		out.printJSon(response);
	}
	
}
